package com.itheima.comment.server.impl;

import com.heima.model.common.comment.pojos.ApComment;
import com.itheima.comment.server.CommentHotService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CommentHotServiceImpl implements CommentHotService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    @Async("taskExecutor")
    public void hotCommentExecutor(ApComment apComment) {
        log.info("异步计算热点文章==================> 开始");
        // 1. 查询当前文章下的所有热点评论集合
        //     1.1 按照文章id   flag=1(热点文章)   点赞降序
        Long articleId = apComment.getArticleId();
        Query query = Query.query(Criteria.where("articleId").is(articleId).and("flag").is(1));
        Sort sort = Sort.by(Sort.Direction.DESC,"likes");
        query.with(sort);// 排序
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        // 2. 如果 热评集合为空  或  热评数量小于5 直接将当前评论改为热评
        if (apComments.isEmpty() || apComments.size()<5){
            Update update = new Update();
            update.set("flag",1);
            Query id = Query.query(Criteria.where("_id").is(apComment.getId()));
            mongoTemplate.updateMulti(id,update,ApComment.class);
        }else {
            // 3. 如果热评数量大于等于 5

            // 3.1  获取热评集合中 最后点赞数量最少的热评
            ApComment apCommentMin = apComments.get(apComments.size() - 1);
            Integer likesMin = apCommentMin.getLikes();
            Integer likesNow = apComment.getLikes();
            Update flag0 = new Update().set("flag", 0);
            Update flag1 = new Update().set("flag", 1);
            Query queryMin = Query.query(Criteria.where("_id").is(apCommentMin.getId()));
            Query queryNow = Query.query(Criteria.where("_id").is(apComment.getId()));
            if (likesNow>=likesMin){
                // 3.2 和当前评论点赞数量做对比  谁的点赞数量多 改为热评
                mongoTemplate.updateMulti(queryNow,flag1,ApComment.class);
                mongoTemplate.updateMulti(queryMin,flag0,ApComment.class);
            }

        }

        log.info("异步计算热点文章==================> 结束");


    }
}
